﻿using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyRead.API.Appicant.Command.Approval;
using MediatR;

namespace B.S.DataBase.MyRead.API.Appicant.CommandHandler.Approval
{
    /// <summary>
    /// 查询同级部门领导
    /// </summary>
    public class PeerlevelApprovalJudgmentCommandHandler : IRequestHandler<PeerlevelApprovalJudgmentCommand, APIResult<object>>
    {
        private readonly IBaseRepository<User> userRep;
        private readonly IBaseRepository<ApprovalRecord> recordRep;

        public PeerlevelApprovalJudgmentCommandHandler(IBaseRepository<User> userRep, IBaseRepository<ApprovalRecord> recordRep)
        {
            this.userRep = userRep;
            this.recordRep = recordRep;
        }

        public async Task<APIResult<object>> Handle(PeerlevelApprovalJudgmentCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<object>();


            // 查询相同部门的部门领导总数
            var totalLeaders =  userRep.GetAll().Result
                .Count(x => x.DepId == request.DepartmentId
                               && x.DepartmentHeadId == 1);

            // 查询该申请的同级审批记录数
            var approvedCount =  recordRep.GetAll().Result
                .Count(x => x.LeaveId == request.LeaveId
                              && x.DepartmentId == request.DepartmentId
                              && x.DepartmentHeadId == 1
                              && x.Status == "通过");

            result.data = new
            {
                totalLeaders,
                approvedCount,
                isAllApproved = approvedCount >= totalLeaders // 新增是否全部审批完成标识
            };
            return await Task.FromResult(result);

        }
    }
}
